<template>
  <div class="card-container">
    <h1>待办事项</h1>
    <div class="button-group">  
    <el-button type="primary" @click="openDialog">添加待办事项</el-button>
  </div>
    <div class="date-picker-container">
      <span>筛选日期</span>
      <el-date-picker
        v-model="dateRange"
        type="datetime"
        placeholder="选择日期范围"
        @change="filterTodos"
      />        
    </div>
 

    <el-dialog title="添加待办事项" v-model="dialogVisible" width="600px" append-to-body>
  <el-form ref="todoForm" :model="newTask" :rules="taskRules" label-width="80px">
    <el-row>
      <el-col :span="12">
        <el-form-item label="任务标题" prop="title">
          <el-input v-model="newTask.title" placeholder="请输入任务标题" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="任务内容" prop="task">
          <el-input v-model="newTask.task" placeholder="请输入任务内容" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="奖惩" prop="item">
          <el-select v-model="newTask.item"   placeholder="选择奖惩">
            <el-option v-for="item in rewardPunishmentList" :key="item.id" :label="item.item"
                                :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="newTask.priority" placeholder="选择优先级">
            <el-option label="高" value="3" />
            <el-option label="中" value="2" />
            <el-option label="低" value="1" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker v-model="newTask.startDate" type="datetime" placeholder="选择开始时间" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="完成时间" prop="dueDate">
          <el-date-picker v-model="newTask.dueDate" type="datetime" placeholder="选择结束时间" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <template #footer>
    <div class="dialog-footer button-group">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addTodo">确 定</el-button>
    </div>
  </template>
</el-dialog>

    <div class="cards">
      <div v-for="todo in filteredTodoList" :key="todo.id" class="card">
        <h4>{{ todo.title }} <span :class="statusClass(todo.status)">{{ statusText(todo.status) }}</span></h4>
        <p>
          {{ todo.task }}
        </p>
        <el-progress :percentage="todo.isCompleted" />
        <p>时间: {{ formatDate(todo.startDate) }} — {{ formatDate(todo.dueDate) }}</p>
        <p>奖惩: {{ todo.item }}</p>
        <!-- <p>优先级: {{ todo.priority }}</p> -->
        <p>创建时间: {{ formatDate(todo.createdAt) }}</p>
        <div class="button-group">
        <el-button type="success">修改</el-button>
        <el-button type="danger" @click="removeTodo(todo.id)">移除</el-button>
        </div>
      </div>
    </div>
  </div>



</template>

<script setup>
import { ref, computed } from 'vue';
import todoEventApi from "@/api/todoEvent"
import {getRewardPunishmentByUserId} from "@/api/rewardPunishment"
import { onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter();

const hasToken = () => {
  // 假设 token 存储在 localStorage 中
  return localStorage.getItem('token') !== null;
};


const rewardDialogVisible = ref(false);



//获取奖惩记录
const rewardPunishmentList = ref([]);
const getRewardPunishmentList = () => {
  getRewardPunishmentByUserId().then(res => {
    if (res.code === 200) {
      rewardPunishmentList.value = res.data;
    }
  })
}




const dateRange = ref([]);
const dialogVisible = ref(false);
const newTask = ref({
  title: '',
  task: '',
  item:null,
  priority: '中',
  status: 0,
  startDate: '',
  dueDate:'',
  isCompleted: 0, 
});
const todoList = ref([
]);

//获取待办事项列表
const getTodoList = () => {
  todoEventApi.getEventListByUserId().then(res => {
    if (res.code === 200) {
      todoList.value = res.data;
    }
  })
}

const filteredTodoList = computed(() => {
  if (!dateRange.value[0] || !dateRange.value[1]) return todoList.value;
  return todoList.value.filter(todo => {
    const startDate = new Date(todo.startDate);
    const dueDate = new Date(todo.dueDate);
    return startDate >= dateRange.value[0] && dueDate <= dateRange.value[1];
  });
});

const openDialog = () => {
  if (!hasToken()) {
    ElMessage({
      type: 'error',
      message: '请先登录',
    });
  }else{
  dialogVisible.value = true;
  }
};
const addTodo = () => {
  if (!newTask.value.title || !newTask.value.task) {
    alert('请填写任务标题和内容');
    return;
  }
  newTask.value.status = 0; // 未开始
  newTask.value.isCompleted = 0; // 未完成
  newTask.value.createdAt = new Date().toISOString(); // 创建时间
  const param={
    title: newTask.value.title,
    task: newTask.value.task,
    rewardId: newTask.value.item,
    priority: newTask.value.priority,
    status: newTask.value.status,
    startDate: newTask.value.startDate,
    dueDate: newTask.value.dueDate,
    isCompleted: newTask.value.isCompleted,
  }
  todoEventApi.createTodoEvent(param).then(res => {
    if (res.code === 200) {
      alert('添加成功');
      getTodoList(); // 更新待办事项列表
      dialogVisible.value = false; // 关闭弹窗
    }
  })
  newTask.value = { title: '', task: '', item: '', priority: '中' }; // 重置表单
  dialogVisible.value = false; // 关闭弹窗
};

const removeTodo = (id) => {
  todoEventApi.deleteTodoEvent(id).then(res => {
    if (res.code === 200) {
      alert('删除成功');
      getTodoList(); // 更新待办事项列表
      }
  })
};

const formatDate = (date) => {
  return new Date(date).toLocaleDateString();
};


const statusClass = (status) => {
  switch (status) {
    case 0: return 'status-upcoming'; // 未开始
    case 1: return 'status-ongoing'; // 正在进行
    case 2: return 'status-completed'; // 已完成
    case 3: return 'status-failed'; // 失败
    default: return '';
  }
};

const statusText = (status) => {
  switch (status) {
    case 0: return '未开始';
    case 1: return '进行中';
    case 2: return '已完成';
    case 3: return '失败';
    default: return '';
  }
};

onMounted(() => {
  getTodoList();
  getRewardPunishmentList();
});
</script>

<style scoped>

  .todo-container {
    display: flex;
   /* Use flexbox for layout */
    min-width: 1420px;
    /* Set minimum width */
    max-width: 1600px;
    align-items: flex-start;
    /* Align items at the start */
    flex-direction: column;
    /* Stack items vertically */ 
    width: 99%;
    margin: 20px auto;
    padding: 20px;
    border: 1px solid #eaeaea;
    border-radius: 8px;
    background-color: #f9f9f9;

    & > .el-tabs {
      margin-top: 20px;
      width: 100%;
      }
  }

  .card-container {
  width: 95%;
  margin: 20px;
  padding: 20px;
  border: 1px solid #eaeaea;
  border-radius: 8px;
  background-color: #f9f9f9;
  /* 换行 */
  flex-wrap: wrap;
  max-width: 100%;
}


.date-picker-container {
  margin-bottom: 20px;
  margin-top: 20px;
}

.cards {
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}

.card {
  /* flex: 1 1 calc(33.333% - 20px); */
  margin: 10px;
  padding: 15px;
  width: 400px;
  border: 1px solid #dcdcdc;
  border-radius: 5px;
  background-color: #ffffff;
}

.status-upcoming {
  color: gray; /* 未开始 */
}

.status-ongoing {
  color: green; /* 正在进行 */
}

.status-completed {
  color: blue; /* 已完成 */
}

.status-failed {
  color: red; /* 失败 */
}
.button-group {
    display: flex; /* 使用 Flexbox 布局 */
    justify-content: space-between; /* 均分一行 */
    margin-top: 10px; /* 按钮与其他内容的间距 */

    & > button {
      width: 100px; /* 按钮宽度 */
      margin-left: 10px; /* 按钮间距 */ 
    }
  }
  
</style>